﻿using System;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using SkyConnector.Model;

namespace SkyConnector.ViewModel
{
    public class MainViewModel : ViewModelBase, INotifyPropertyChanged
    {
        private Temperature mActualTemperature;
        private bool doStopServer = false;
        private Socket server;
        private Thread myThread;
        private CloudConnection cloudConn;

        public MainViewModel()
        {
            toggleServer = new RelayCommand(ToggleServerExecute);
            mActualTemperature = new Temperature();

            const Int32 c_port = 2000;

            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, c_port);
            server.Bind(localEndPoint);
            server.Listen(Int32.MaxValue);

            cloudConn = new CloudConnection();
        }

        public Temperature actualTemperature
        {
            get
            {
                return mActualTemperature;
            }

            set
            {
                mActualTemperature = value;
                Notify("actualTemperature");
            }
        }

        private string mStatus = "Ready";
        public string status
        {
            get { return mStatus; }
            set { mStatus = value; Notify("status");}
        }

        private string mToggleServerButtonText = "Start";
        public string toggleServerButtonText
        {
            get { return mToggleServerButtonText; }
            set { mToggleServerButtonText = value; Notify("toggleServerButtonText"); }
        }

        private bool mBTNstartStopEnabled = true;
        public bool BTNstartStopEnabled 
        { 
            get { return mBTNstartStopEnabled; }

            set { mBTNstartStopEnabled = value; Notify("BTNstartStopEnabled"); }
        }

        public ICommand toggleServer
        {
            get;
            private set;
        }

        private void ToggleServerExecute()
        {
            if(myThread == null || !myThread.IsAlive)
            {
                doStopServer = false;
                myThread = new Thread(StartServer);
                myThread.Start();
                status = "Server started";
                toggleServerButtonText = "Stop";
            }

            else
            {
                doStopServer = true;
                status = "Waiting for server to stop...";
                toggleServerButtonText = "Wait...";
                BTNstartStopEnabled = false;
            }
        }

        private void StartServer()
        {
            doStopServer = false;
            Socket clientSocket;
            localConnection conn;

            while(!doStopServer)
            {
                status = "Waiting for data...";

                // Wait for a client to connect.
                clientSocket = server.Accept();

                status = "Retreiving data...";

                // Process the client request.  true means asynchronous.
                conn = new localConnection(clientSocket, false);
                var temp = new Temperature {temperature = conn.getReceivedInteger()};
                actualTemperature = temp;

                status = "Uploading data...";
                status = cloudConn.uploadToDatabase(conn.getReceivedInteger());
            }

            status = "Server stopped";
            toggleServerButtonText = "Start";
            BTNstartStopEnabled = true;
        }

        new public event PropertyChangedEventHandler PropertyChanged;
        protected void Notify(string propName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }
    }
}